<?php

/**
 * @file
 * Adds events to database.
 *
 * Copyright 2011 by UNHM CIS605 project Donate team.
 * This program is part of BBBS and YWCA Donation management system.
 * Donate is free software. It comes with absolutely no warranty.
 * You can redistribute it and/or modify it under the terms of the GNU
 * General Public License as published by the Free Software Foundation
 * (see <http://www.gnu.org/licenses/ for more information).
 *
 * @version March 7, 2011
 * @author Laura Cassella
 */
/**
 * Functions to create, add, update, delete, get, getall and select from the
 * dbEvent table in the database. This table is used with the Event class.
 */

/**
 * Creates the dbEvent table in the database.
 * @return TRUE or FALSE. FALSE on failure.
 */
include_once('dbConnect.php');
include_once('../model/Event.php');
Class dbEvent {

	/**
	 *this function sets up the database for donor.
	 *@param
	 *@return
	 */
	static function createTable() {

		$query =("CREATE  TABLE event (
  eventID     INT         NOT NULL AUTO_INCREMENT ,
  eventTypeID INT         NOT NULL ,
  eventDate   DATE        NULL ,
  street      VARCHAR(25) NULL ,
  city        VARCHAR(15) NULL ,
  stateName   VARCHAR(2)  NULL ,
  zip         VARCHAR(10) NULL ,
 CONSTRAINT pk_event PRIMARY KEY (eventID),
 CONSTRAINT fk_eventType_event FOREIGN KEY (eventTypeID)
	REFERENCES eventType (eventTypeID)ON DELETE CASCADE ON UPDATE CASCADE
);
  ");

		connect();
		$result = mysql_query($query);
		echo mysql_error();
		mysql_close();
		if ($result == false) {
			return false;
		}

		//Previous query was successful.
		return true;
	}


	static function verifyInsertedEvent($id)
	{
		$output = "";
		$error = dbEvent::getAllByID($id, $output);
		if ($error == true) {
			printf("%s<br />", $output);
		}
		else {
			$ind = new Event($output['eventTypeID'], $output['eventDate'], $output['street'], $output['city'], $output['stateName'], $output['zip']);
			printf("Inserted: Event with ID=%d has %s.<br />", $id, $ind->printAllAttributes( ));
		}
	}

	static function addEventByFields($eventTypeID,$eventDate,$street,$city,$stateName,$zip, &$id)
	{
		$e = new Event($eventTypeID,$eventDate,$street,$city,$stateName,$zip);
		$result = dbEvent::addEvent($e, $id);
		if ($result == false) {
			die ("Event could not be updated with specified information.<br />");
		}
	}
	/**
	 * Add an event to the dbEvent table.
	 * @param int $i the auto-generated eventID
	 */
	static function addEvent($v, &$id) {
		if (!$v instanceof event) {
			echo ("Invalid arguement insertInto ( ) function<br />");
			return false;
		}
		//Compose the INSERT INTO query srting. Primary key value is missing.
		//Database server automatically generates a unique ID for the primary Key.
		$query = sprintf("INSERT INTO event VALUES(null, %d, '%s', '%s', '%s', '%s', '%s')",
		$v->getEventTypeID(),
		$v->getEventDate(),
		$v->getStreet(),
		$v->getCity(),
		$v->getStateName(),
		$v->getZip()
		);
		connect( );
		$result = mysql_query($query);
		//printf("Event added has id %d\n<br />", mysql_insert_id());
		$id = mysql_insert_id( );
		mysql_close( );
		if ($result == false) {
			echo mysql_error();
			return false;
		}
		//query was successful.
		return true;
	}

	/**
	 * Remove an event from the dbEvent table.
	 * @return TRUE or FALSE. FALSE on failure.
	 */
	function deleteEvent($i) {
		connect();
		$query = 'SELECT * FROM dbEvent WHERE eventID = "' . $eventID . '"';
		$result = mysql_query($query);
		if ($result == null || mysql_num_rows($result) == 0) {
			mysql_close();
			return false;
		}
		$query = 'DELETE FROM dbEvent WHERE eventID = "' . $eventID . '"';
		mysql_close();
		return true;
	}

	/**
	 * Get a single row from the dbEvent table matching a particular eventID.
	 * @return TRUE or FALSE. FALSE on failure.
	 */
	function geteventID($i) {
		connect();
		$query = 'SELECT * FROM dbEvent WHERE eventID = "' . $eventID . '"';
		$result = mysql_query($query);
		if ($result == null || mysql_num_rows($result) !== 1) {
			mysql_close();
			return false;
		} else {
			$result = true;
			mysql_close();
		}
		return $result;
	}

	/**
	 * Get all rows from the dbEvent table ordered by eventDate.
	 * @return TRUE or FALSE. FALSE on failure.
	 */
	function getallEvents($ed) {
		connect();
		$query = "SELECT * FROM dbEvent ORDER BY eventDate";
		$result = mysql_query($query);
		if ($result == null || mysql_num_row($result) == 0) {
			mysql_close();
			return false;
		} else {
			$result = true;
			mysql_close();
		}
		return result;
	}

	/**
	 * Updates an event date in the database by deleting it (if it exists) and then replacing it.
	 * @param date $ed replace date.
	 */
	function updatedbEvent($ed) {
		connect();
		$query = "UPDATE dbEvent " .
            "SET eventDate = '' " .
            "WHERE eventDate = ''";
		$result = mysql_query($query);
		mysql_close();
	}


	/**
	 * Selects all events from the database for a given date.
	 * @param date $ed is an event date.
	 * @return a result set or false.
	 */
	function selectdbEvent($ed) {
		connect();
		$query = "SELECT * FROM dbEvent WHERE =\"" . $ed . "\"";
		$result = mysql_query($query);
		if (!$result) {
			echo 'Could not run query: ' . mysql_error();
			mysql_close();
			return false;
		}
		mysql_close();
		return true;
	}

	public static function getAllByID($id, &$output) {
		$query = sprintf("SELECT eventTypeID, eventDate, street, city, stateName, zip FROM event WHERE eventID=%d",
		$id);
		// printf("->Query: %s<br />", $query);

		connect( );
		$result = mysql_query($query);
		mysql_close( );

		if ($result == false) {
			$output = sprintf("%s", mysql_error());
			return false;
		}
		//process result and print out warning or attribute values
		return dbEvent::checkForOneInstance($result, $id, $output);
	}

	private static function checkForOneInstance($result, $id, &$output)
	{
		//Local variables are initialized.
		//Think positively about what this checking returns :-) and set $errorStatus
		//to initial value false
		$errorStatus = false;

		$howMany = mysql_num_rows($result);
		// printf("-->Found %d instance(s) for donorID=%d.<br />", $howMany, $id);
		switch ($howMany) {
			case 0:
				$output = sprintf("No event instance with ID=%d was found.",
				$id);
				$errorStatus = true;
				break;
			case 1:
				//mysql_fetch( ) DOES NOT return primary key values!
				$output = mysql_fetch_assoc($result);
				$errorStatus = false;
				break;
			default:
				$output = sprintf("There are multiple event instances
                           with ID=%d.", $id);
				$errorStatus = true;
				break;
		}
		return $errorStatus;
	}

}
?>